package com.ycx.furns.web;

import com.google.gson.Gson;
import com.ycx.furns.entity.Member;
import com.ycx.furns.utils.WebUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AuthFilter implements Filter {
    List<String> excludedUrlList;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludedUrls = filterConfig.getInitParameter("excludedUrls");
        String[] split = excludedUrls.split(",");
        excludedUrlList = Arrays.asList(split);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String servletPath = ((HttpServletRequest) servletRequest).getServletPath();
        if(!excludedUrlList.contains(servletPath)) {
            Member member = (Member) req.getSession().getAttribute("member");
            if (member == null ) {
                System.out.println("经过过滤器~~");
                if(!WebUtils.isAjaxRequest(servletRequest)){
                    req.getRequestDispatcher("/views/member/login.jsp").forward(servletRequest, servletResponse);
                }else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("url", "views/member/login.jsp");
                    String json = new Gson().toJson(map);
                    servletResponse.getWriter().write(json);
                }

                return;
            }

        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
